<?php
namespace Api\Controller;
use Think\Controller;
class HomeController extends Controller {
    public function _initialize(){
		// 加载配置
		$_CFG = F("Config");
		$arr_key = F("ArrKey");
		if(empty($_CFG) || empty($arr_key)){
			$config = M('config') -> select();
			if(!is_array($config)){
				die('请先在后台设置好各参数');
			}
			foreach($config as $v){
				$key = '_'.$v['name'];
				$this -> $key = unserialize($v['value']);
				$_CFG[$v['name']] = $this -> $key;
				$arr_key[$key] = $this -> $key;
			}
			F("Config",$_CFG);
			F("Arrkey",$arr_key);
		}else{
			foreach ($arr_key as $key => $v){
				$this -> $key = $v;
			}
		}
		$this -> assign('_CFG', $_CFG);
		$GLOBALS['_CFG'] = $_CFG;
		
		// _开头的函数为内部函数，不能直接访问
		if(substr(ACTION_NAME,0,1) == '_'){
			error('访问地址错误！');
		}
		//print_r($this -> _level);
		
		/* if(APP_DEBUG && $_GET['user_id'])
			session('user', M('user') -> find(intval($_GET['user_id'])));

		//$this -> tplmsg = new \Common\Util\tplmsg;
		
		if(session('?user') && empty($_GET['spm'])){
			// 不能直接从session获取数据，不是最新的 
			$this -> user = M('user') -> find(session('user.id'));
		}else{
			// 网页认证授权
			if (!isset($_GET['code'])){
				$custome_url = get_current_url();
				$scope = 'snsapi_userinfo';
				$oauth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this -> _mp['appid'] . '&redirect_uri=' . urlencode($custome_url) . '&response_type=code&scope=' . $scope . '&state=dragondean#wechat_redirect';
				header('Location:' . $oauth_url);
				exit;
			}
			if(isset($_GET['code']) && isset($_GET['state']) && isset($_GET['state']) == 'dragondean'){
				$rt = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this -> _mp['appid'] . '&secret=' . $this -> _mp['appsecret'] . '&code=' . $_GET['code'] . '&grant_type=authorization_code');
				$jsonrt = json_decode($rt, 1);
				if(empty($jsonrt['openid'])){
					$this -> error('用户信息获取失败!');
				}
				$this -> openid = $jsonrt['openid'];
				
				//从数据库获取信息
				$user_info = M('user') -> where(array('openid' => $this -> openid)) -> find();
				
				// 验证是否关注
				$dd = new \Common\Util\ddwechat($this -> _mp);
				$accesstoken = $dd -> getaccesstoken();
				//$rt = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this -> _mp['appid'] . '&secret=' . $this -> _mp['appsecret']);
				//$gz_jsonrt = json_decode($rt ,1);
				$rt = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$accesstoken."&openid=".$this -> openid."&lang=zh_CN");
				$gz_jsonrt = json_decode($rt ,1);
				if($gz_jsonrt['subscribe'] == 0){
					header('Location:http://mp.weixin.qq.com/s/48fNX_1Cla9GDHUlSNyVSw');
					exit;
				} 
				
				if(!$user_info){
					// 拉取用户信息
					$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$jsonrt['access_token']."&openid=".$jsonrt['openid']."&lang=zh_CN";
					$rt = file_get_contents($url);
					$jsonrt = json_decode($rt ,1);
					if(empty($jsonrt['openid'])){
						$this -> error('获取用户详细信息失败');
					}
					$user_info = array(
						'nickname' => $jsonrt['nickname'],
						'openid' => $this -> openid,
						'sex' => $jsonrt['sex'],
						'headimg' => $jsonrt['headimgurl'],
						'parent1' => intval($_GET['parent']),
						'subscribe' => 1
					);
					if($_GET['parent']){
						$parent_info = M('user') -> find(intval($_GET['parent']));
						if($parent_info){
							$user_info = array_merge(array(
								'parent1' => $parent_info['id'],
								'parent2' => $parent_info['parent1'],
								'parent3' => $parent_info['parent2']
							), $user_info);
						}
					}
					
					$user_info['id'] = M('user') -> add($user_info);
					if($user_info['id']){
						if($parent_info['id'])M('user') -> where('id='.$parent_info['id']) -> setInc('agent1');
						if($parent_info['parent1'])M('user') -> where('id='.$parent_info['parent1']) -> setInc('agent2');
						if($parent_info['parent2'])M('user') -> where('id='.$parent_info['parent2']) -> setInc('agent3');
					}
					//$user_info = M('user') -> find($user_id);
				}
				session('user', $user_info);
				$this -> user = $user_info;
			}
		}
		
		$this -> assign('user', $this -> user);
		
		// 自动确认收货
		$this -> _auto_confirm();
		
		// 需要鉴定分销权限的模块
		$dist_arr = array( 'my_agent', 'separate', 'qrcode', 'get_qrcode','myshop');
		if(in_array(ACTION_NAME, $dist_arr) && !$this -> _can('dist') && $this -> user['dist']!=1){ // 所在等级没有分销权限，且没有设置的分销权限
			$this -> error('您没有分销权限！');
		}
		
		// 需要提现权限的模块
		$withdraw_arr = array( 'withdraw', 'withdraw_add');
		if(in_array(ACTION_NAME, $withdraw_arr) && !$this -> _can('withdraw')){
			$this -> error('您没有提现权限！');
		}
		
		// 需要转让权限的模块
		$deposit_arr = array('deposit','deposit_add');
		if(in_array(ACTION_NAME, $deposit_arr) && !$this -> _can('deposit')){
			$this -> error('您没有转让权限！');
		}
		
		// 调用jssdk
		$dd = new \Common\Util\ddwechat();
		$dd -> setParam($this -> _mp);
		$jssdk = $dd -> getsignpackage();
		$this -> assign('jssdk', $jssdk); */
	}
	
	
	// 判断权限
	private function _can($type){
		if($type == 'dist'){
			return $this -> user['dist'] == 1 || $this -> _level[$this -> user['level']][$type]==1 ? true : false ;
		}else{
			if($this -> _level[$this -> user['level']][$type] > 0){
				return true;
			}else{
				return false;
			}
		}
	}
	
	// 自动确认收货
	private function _auto_confirm(){
		if(!empty($this -> _site['auto_confirm']) && $this -> _site['auto_confirm'] >0){
			$time = strtotime('-'.$this -> _site['auto_confirm'].'days');
			// 所有发货时间超过制定时间的待收货的订单
			$orders = M('order') -> where(array(
				'delivery_time' => array('lt', $time),
				'status' => 3
			)) -> select();
			foreach($orders as $order_info){
				confirm_order($order_info);
			}
		}
	}
}